package 二叉树;

public class LC_112路径总和 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null) return false;
        targetSum-=root.val;
        if(root.left==null && root.right==null && targetSum==0)
            return true;
        if(root.left==null && root.right==null && targetSum!=0)
            return false;
        if(root.left!=null){
//            targetSum-=root.left.val;
            if(hasPathSum(root.left,targetSum))
                return true;
//            targetSum+=root.left.val;//回溯
        }
        if(root.right!=null){
//            targetSum-=root.right.val;
            if(hasPathSum(root.right,targetSum))
                return true;
//            targetSum+=root.right.val;//回溯
        }
        return false;
    }
}
